package net.esj.basic.utils;

import java.security.AccessController;
import java.security.PrivilegedAction;

public class GetClassLoader implements PrivilegedAction<ClassLoader> {

	private final Class<?> clazz;

	public static ClassLoader fromContext() {
		final GetClassLoader action = new GetClassLoader( null );
		if ( System.getSecurityManager() != null ) {
			return AccessController.doPrivileged( action );
		}
		else {
			return action.run();
		}
	}

	public static ClassLoader fromClass(Class<?> clazz) {
		if ( clazz == null ) {
			throw new IllegalArgumentException( "Class is null" );
		}
		final GetClassLoader action = new GetClassLoader( clazz );
		if ( System.getSecurityManager() != null ) {
			return AccessController.doPrivileged( action );
		}
		else {
			return action.run();
		}
	}

	private GetClassLoader(Class<?> clazz) {
		this.clazz = clazz;
	}

	public ClassLoader run() {
		if ( clazz != null ) {
			return clazz.getClassLoader();
		}
		else {
			return Thread.currentThread().getContextClassLoader();
		}
	}
}
